package com.heima.wemedia.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.heima.apis.article.IArticleClient;
import com.heima.common.aliyun.GreenImageScan;
import com.heima.common.aliyun.GreenTextScan;
import com.heima.common.tess4j.Tess4jClient;
import com.heima.file.service.FileStorageService;
import com.heima.model.article.dtos.ArticleDto;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.wemedia.pojos.WmChannel;
import com.heima.model.wemedia.pojos.WmNews;
import com.heima.model.wemedia.pojos.WmSensitive;
import com.heima.model.wemedia.pojos.WmUser;
import com.heima.utils.common.SensitiveWordUtil;
import com.heima.wemedia.mapper.WmChannelMapper;
import com.heima.wemedia.mapper.WmNewsMapper;
import com.heima.wemedia.mapper.WmSensitiveMapper;
import com.heima.wemedia.mapper.WmUserMapper;
import com.heima.wemedia.service.WmNewsAutoScanService;
import com.netflix.client.IClient;
import lombok.extern.slf4j.Slf4j;
import net.sourceforge.tess4j.TesseractException;
import org.apache.avro.data.Json;
import org.apache.commons.lang.StringUtils;
import org.checkerframework.checker.guieffect.qual.AlwaysSafe;
import org.checkerframework.checker.units.qual.A;
import org.simpleframework.xml.ElementArray;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;

@Service
@Transactional
@Slf4j
public class WmNewsAutoScanServiceImpl implements WmNewsAutoScanService {

    @Autowired
    private WmNewsMapper wmNewsMapper;

    //图片审核
    @Autowired
    private GreenImageScan greenImageScan;

    //文本审核
    @Autowired
    private GreenTextScan greenTextScan;

    //图片下载
    @Autowired
    private FileStorageService fileStorageService;

    //TODO 调用远程接口
    @Autowired
    private IArticleClient iArticleClient;

    @Autowired
    private WmChannelMapper wmChannelMapper;

    @Autowired
    private WmUserMapper wmUserMapper;

    //敏感词过滤
    @Autowired
    private WmSensitiveMapper wmSensitiveMapper;

    /**
     * 自媒体文章审核
     *
     * @param id 自媒体文章id
     */

    @Override
    //@Async   //TODO 标明当前方法是一个异步方法
    public void autoScanWmNews(Integer id) {

        /*
        //测试异步调用
        int a = 1 / 0; */

        //1.查询自媒体文章
        WmNews wmNews = wmNewsMapper.selectById(id);
        if (wmNews == null) {
            log.info("WmNewsAutoScanServiceImpl-文章不存在");
            throw new RuntimeException("WmNewsAutoScanServiceImpl-文章不存在");
        }
        //先判断是否是待审核的状态 或者未通过审核状态
        if (wmNews.getStatus().equals(WmNews.Status.SUBMIT.getCode())) {

            //从内容中提取村文本内容和图片
            Map<String, Object> textAndImages = handleTextAndImages(wmNews);

            //2.1 审核文本内容  阿里云接口
            boolean isTextScan = handleTextScan((String) textAndImages.get("context"), wmNews);
            if (!isTextScan) return;

            //2.2 审核文本 自管理的敏感词过滤
            boolean isSensitive = handleSensitiveScan((String) textAndImages.get("context"), wmNews);
            if (!isSensitive) return;

            //3.1 审核图片  阿里云接口
            boolean isImageScan = handleImageScan((List<String>) textAndImages.get("images"), wmNews);
            if (!isImageScan) return;

            AuthPass(wmNews);
        }
        //人工审核通过
        else if (wmNews.getStatus().equals(WmNews.Status.ADMIN_SUCCESS.getCode())) {
            AuthPass(wmNews);
        } else {
            log.error("(异步)当前事务还提交 未读到更新后的数据" + "文章状态为:----" + wmNews.getStatus());
        }
    }


    //机器审核和人工审核都通过 保存app端数据
    public void AuthPass(WmNews wmNews) {
        log.error("同步调用：" + "文章状态为:----" + wmNews.getStatus());
        //TODO 4 .审核成功 保存app端相关的文章数据
        ResponseResult responseResult = saveAppArticle(wmNews);

        if (!responseResult.getCode().equals(200)) {
            log.info("WmNewsAutoScanServiceImpl-文章审核保存app端相关文章数据失败");
            throw new RuntimeException("WmNewsAutoScanServiceImpl-文章审核保存app端相关文章数据失败");
        }
        //5. 保存成功 回填article_id
        wmNews.setArticleId((Long) responseResult.getData());
        wmNews.setStatus((short) 9);
        wmNews.setReason("审核成功");
        wmNewsMapper.updateById(wmNews);
        log.info("文章发布成功");
    }

    /**
     * 自管理的敏感词过滤
     *
     * @param context
     * @param wmNews
     * @return
     */
    private boolean handleSensitiveScan(String context, WmNews wmNews) {

        boolean flag = true;

        //获取所有的敏感词
        LambdaQueryWrapper<WmSensitive> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.select(WmSensitive::getSensitives);
        List<WmSensitive> wmSensitives = wmSensitiveMapper.selectList(lambdaQueryWrapper);

        List<String> collect = wmSensitives.stream().map(WmSensitive::getSensitives).collect(Collectors.toList());
        //初始化敏感词库
        SensitiveWordUtil.initMap(collect);
        //看出文章或（图片中的文字）中是否有敏感词
        Map<String, Integer> map = SensitiveWordUtil.matchWords(context + wmNews.getTitle()); //标题也需判断
        if (map.size() > 0) {
            log.info("当前文章内容或标题存在敏感词{},需要人工审核", map);
            flag = false;
            wmNews.setStatus((short) 3);
            wmNews.setReason("存在违规内容==>" + map);
            wmNewsMapper.updateById(wmNews);
        }

        return flag;
    }


    /**
     * 保存app端相关的文章数据
     *
     * @param wmNews
     */
    private ResponseResult saveAppArticle(WmNews wmNews) {

        ArticleDto dto = new ArticleDto();

        //属性拷贝
        BeanUtils.copyProperties(wmNews, dto);
        //文章的布局
        dto.setLayout(wmNews.getType());
        //频道名称
        WmChannel wmChannel = wmChannelMapper.selectById(wmNews.getChannelId());
        if (wmChannel != null) {
            dto.setChannelName(wmChannel.getName());
        }
        //作者
        dto.setAuthorId(wmNews.getUserId().longValue());
        WmUser wmUser = wmUserMapper.selectById(wmNews.getUserId());
        if (wmUser != null) {
            dto.setAuthorName(wmUser.getName());
        }
        if (wmNews.getArticleId() != null) {
            dto.setId(wmNews.getArticleId());
        }
        dto.setCreatedTime(new Date());

        //TODO 调用远程接口
        return iArticleClient.saveArticle(dto);

    }


    //图片识别文章
    @Autowired
    private Tess4jClient tess4jClient;

    /**
     * 审核图片
     * 因为安全接口有问题 所以直接审核成功
     *
     * @param images
     * @param wmNews
     * @return
     */
    private boolean handleImageScan(List<String> images, WmNews wmNews) {

        boolean flag = true;


        /*if (images.size() == 0 || images == null) {
            return flag;
        }

        //下载图片从minio中
        //图片去重
        List<byte[]> imageList = new ArrayList<>();
        images = images.stream().distinct().collect(Collectors.toList());

        try {
            for (String image : images) {

                byte[] bytes = fileStorageService.downLoadFile(image);
                //byte数组转化为bufferImage
                ByteArrayInputStream in = new ByteArrayInputStream(bytes);
                BufferedImage read = ImageIO.read(in);

                //3.2 审核图片  自定义识别图片
                String result = tess4jClient.doOCR(read);

                //将识别到的文字进行敏感词过滤
                boolean isSensitive = handleSensitiveScan(result, wmNews);
                if (!isSensitive){
                    return false;
                }

                imageList.add(bytes);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        try {
            Map map = greenImageScan.imageScan(imageList);
            if (map != null) {

                //审核失败
                if (map.get("suggesiton").equals("block")) {
                    flag = false;
                    wmNews.setStatus((short) 2);
                    wmNews.setReason("当前图片中存在违规内容");
                    wmNewsMapper.updateById(wmNews);
                }
                //不确定信息 需要人工审核
                if (map.get("suggesiton").equals("block")) {
                    flag = false;
                    wmNews.setStatus((short) 3);
                    wmNews.setReason("当前图片中存在不确定内容");
                    wmNewsMapper.updateById(wmNews);
                }
            }
        } catch (Exception e) {
            flag = false;
            e.printStackTrace();
        }
        */
        return flag;
    }

    /**
     * 审核文本
     * 因为安全接口有问题 所以直接审核成功
     *
     * @param context
     * @param wmNews
     * @return
     */
    private boolean handleTextScan(String context, WmNews wmNews) {

        boolean flag = true;
        /*if ((wmNews.getTitle() + "-" + context).length() == 0) {
            return flag;
        }
        try {
            Map map = greenTextScan.greeTextScan(wmNews.getTitle() + "-" + context);
            if (map != null) {

                //审核失败
                if (map.get("suggesiton").equals("block")) {
                    flag = false;
                    wmNews.setStatus((short) 2);
                    wmNews.setReason("当前文章中存在违规内容");
                    wmNewsMapper.updateById(wmNews);
                }
                //不确定信息 需要人工审核
                if (map.get("suggesiton").equals("block")) {
                    flag = false;
                    wmNews.setStatus((short) 3);
                    wmNews.setReason("当前文章中存在不确定内容");
                    wmNewsMapper.updateById(wmNews);
                }
            }
        } catch (Exception e) {
            flag = false;
            e.printStackTrace();
        }*/
        return flag;
    }

    /**
     * 提取村文本内容和图片
     *
     * @param wmNews
     * @return
     */
    private Map<String, Object> handleTextAndImages(WmNews wmNews) {

        Map<String, Object> imageAndText = new HashMap<>();

        //存储纯文本内容
        StringBuilder stringBuilder = new StringBuilder();
        //存放图片和封面

        List<String> images = new ArrayList<>();

        //1.正文
        String content = wmNews.getContent();
        if (StringUtils.isNotBlank(content)) {
            List<Map> maps = JSON.parseArray(content, Map.class);
            for (Map map : maps) {
                String type = (String) map.get("type");   //image or text
                if (type.equals("text")) {
                    stringBuilder.append(map.get("value"));
                }
                if (type.equals("image")) {
                    images.add(map.get("value").toString());
                }
            }
        }

        //2.封面图片
        if (StringUtils.isNotBlank(wmNews.getImages())) {
            String[] split = StringUtils.split(wmNews.getImages(), ",");
            images.addAll(Arrays.asList(split));
        }
        //返回结果
        imageAndText.put("context", stringBuilder.toString());
        imageAndText.put("images", images);
        return imageAndText;
    }
}
